var json={
	//初始化函数
	init:function(){
		var oTab=document.querySelector('.tab');
		var str='';
		var id=1;
		for(var i=0;i<4;i++){
			str+='<tr>';
			for (var j = 0; j < 4; j++) {
				str+='<td id="'+ id++ +'"></td>';
			}
			str+='</tr>';
		}
		oTab.innerHTML=str;
		this.randomNum();
		this.randomNum();
		this.result();
	},
	//创建一个任意区间的随机函数
	myRandom:function(min,max){
		return Math.round(Math.random()*(max-min)+min);
	},
	//随机在格子上生成数字
	randomNum:function(){
		var num=this.myRandom(1,16);
		var oGrid=document.getElementById(num);
		if(oGrid.innerHTML===''){
			oGrid.innerHTML=this.myRandom(1,2)*2;
		}else{
			this.randomNum();
		}
	},
	//改变颜色计算结果函数
	result:function(){
		var color={'':'#fff','2':'#00ff00','4':'#00ccff','8':'#ff9900','16':'#00cc66','32':'#ffcccc','64':'#ff33ff','128':'#0066cc','256':'#6633cc','512':'#ff0099','1024':'#990033','2048':'#6600ff','4096':'#cc0066'};
		var score=0
		for (var i = 1; i <= 16 ;i++) {
			var oGrid=document.getElementById(i);
			oGrid.style.backgroundColor=color[oGrid.innerHTML];
			score+=oGrid.innerHTML*10;
		}
		document.querySelector('.score').innerHTML=score;
	},
	//移动和合并检测
	change:function(before,after){
		//移动
		if (before.innerHTML===''&&after.innerHTML!=='') {
			before.innerHTML=after.innerHTML;
			after.innerHTML='';
		}
		//合并
		if (before.innerHTML!==''&&after.innerHTML===before.innerHTML) {
			before.innerHTML*=2;
			after.innerHTML='';
		}
	},
	//上键
	top:function(){
		for (var i = 1; i <= 4; i++) {
			for(var j = i; j <=i + 12; j += 4) {
				for(var k = j; k > 4; k -= 4){
					var before=document.getElementById(k-4);
					var after=document.getElementById(k);
					this.change(before,after);
				}
			}
		}
	},
	//下键
	bottom:function(){
		for (var i = 1; i <= 4; i++) {
			for(var j = i+12; j >=i; j -= 4) {
				for(var k = j; k < 13; k += 4){
					var before=document.getElementById(k+4);
					var after=document.getElementById(k);
					this.change(before,after);
				}
			}
		}
	},
	//左键
	left:function(){
		for (var i = 1; i <= 13; i+=4) {
			for (var j = i; j <= i+3; j++) {
				for (var k = j; k > i ; k--) {
					var before=document.getElementById(k-1);
					var after=document.getElementById(k);
					this.change(before,after);
				}
			}
		}
	},
	//右键
	right:function(){
		for (var i = 1; i <= 13; i+=4) {
			for (var j = i+4; j >=i; j--) {
				for (var k = j; k < i+3 ; k++) {
					var before=document.getElementById(k+1);
					var after=document.getElementById(k);
					this.change(before,after);
				}
			}
		}
	}
}
window.onload=json.init();
document.onkeydown=function(e){
	if (/13/.test(e.keyCode)) json.init();   //enter初始化
	if(/37/.test(e.keyCode)) json.left();
	else if(/38/.test(e.keyCode)) json.top();
	else if(/39/.test(e.keyCode)) json.right();
	else if(/40/.test(e.keyCode)) json.bottom();
	if(e.keyCode>=37&&e.keyCode<=40){
		json.randomNum();
	}
	json.result();
}